/**
	version:0.0.1
	author:arthur.wang(fnghwsj@gmail.com)
*/
(function($){
	var defaults={
		container:"111",//展示graph的容器id
		url:"111",//调取后台数据的url
		mainLineColor:"#cc0000",
		mainLinePointColor:"#cc0000",
		subLineColor:"#00cc8e",
		subLinePointColor:"#00cc8e",
		textArrowColor:"#7F8C8D",
		textWrapColor:"#7F8C8D",
		mainLineLeftDistance:210//主线距离左边的距离
	};

	var cvs=[
		'<svg height="100%" version="1.1" width="100%" xmlns="http://www.w3.org/2000/svg" style="overflow: hidden; position: relative; left: -0.5px;">',
		'Sorry, your browser does not support inline SVG!',
		'<g>'
	];

	//设置选项
	var options={};
	//全局变量
	var global={
		height:60,
		mainNodes:[],
		mainLinePoints:[],
		allNodes:[]
	};

	$.fn.drawCVSGraph=function(settings){
		var $this=$(this);
		options=$.extend(defaults,settings);
		return this.each(function(){
			var cvsHtml=_draw().join("");
			$this.html(cvsHtml);
			$this.prepend('<div id="nodeInfo" style="position:relative;"></div>');
			_bindEvent(this.id);
		});
	};

	var _bindEvent=function(svgWrapId){
		var menuHtml=[
				'<div class="infoWrap">',
					'<dl class="dl-horizontal">',
  						'<dt>版本</dt>',
  						'<dd>...</dd>',
  						'<dt>时间</dt>',
  						'<dd>...</dd>',
					'</dl>',
				'</div>'
			];

		var versionInfo=[

		];
		$('#'+svgWrapId).on('click','circle',function(e){
			// menuHtml[0]='<div class="menuWrap" style="left:'+(e.pageX+10)+'px;top:'+(e.pageY+10)+'px">'
			// $('body').append(menuHtml.join(""));
		});

		$('#'+svgWrapId).on('mouseout','circle',function(e){
			
		});

		//生成版本信息并且显示
		$('#'+svgWrapId).find('circle.mainPoint').each(function(i,v){
			var $this=$(v);
			var x=$this.attr('cx');
			var y=$this.attr('cy');
			var str=$this.attr('data-node');
			if(typeof str=='undefined'){
				return;
			}
			str=str.replace(/\'/g, "\"");
			var dataObj=JSON.parse(str);
			menuHtml[0]='<div class="infoWrap" style="left:'+(parseInt(x)-153)+'px;top:'+(parseInt(y)-25)+'px">';
			menuHtml[3]='<dd>'+dataObj.data.version+'</dd>';
			menuHtml[5]='<dd>'+dataObj.data.createTime+'</dd>'
			$('#nodeInfo').append(menuHtml.join(""));
		});

		$('.infoWrap').hover(function(e){
			//over
			var $t=$(this);
			var zIndex=$t.css('z-index');
			$t.css('z-index',parseInt(zIndex)+1);
		},function(e){
			//out
			var $t=$(this);
			var zIndex=$t.css('z-index');
			$t.css('z-index',parseInt(zIndex)-1);
		});
	};
	
	

	var _draw=function(){
		//载入数据,后台返回的是一棵树
		var jsonMessage=_loadData(options.url);
		//节点集合
		var nodeTree=jsonMessage.data.list;
		// var height=_forecastHeight(nodeTree);

		//先根遍历得到的队列
		var queue=_travelTree(nodeTree);

		//nodeArray按先序遍历的数组
		var height=0;
		var nodeArray=_countPosition(queue,height);

		for(var i=0;i<nodeArray.length;i++){
			var node=nodeArray[i];
			node.point.y=global.height-node.point.y;
		}

		//广度优先遍历树
		var root={};
		root.childrenVersion=nodeTree;
		var levelArray=_levelSearchTree(root);

		//画线
		_drawLine(levelArray);

		//画版本信息文本框
		_drawVersionText(nodeArray);


		//画点坐标
		for(var i=0;i<nodeArray.length;i++){
			var node=nodeArray[i];
			
			if(node.data.parentVersionId=='0'){
				cvs.push(_drawPointAndInfo(node,options.mainLinePointColor));
			}else{
				cvs.push(_drawPointAndInfo(node,options.subLinePointColor));
			}
		}
		//闭合标签
		cvs[0]='<svg height="'+(global.height+80)+'" version="1.1" width="100%" xmlns="http://www.w3.org/2000/svg" style="overflow: hidden; position: relative; left: -0.5px;">';
		cvs.push('</g>');
		cvs.push('</svg>');

		return cvs;
	};

	var _countPosition=function(queue,height){
		//返回按先序遍历的数组
		var pt={
			x:options.mainLineLeftDistance,
			y:0
		};

		var newArray=[];
		while(!queue.IsEmpty()){
			var node=queue.DeQueue();
			newArray.push(node);
		}
		var lastNode={};
		for(var i=0;i<newArray.length;i++){
			var node=newArray[i];
			if(i==0){
				var nPt={};
				nPt.x=pt.x;
				nPt.y=pt.y;
				node.point=nPt;
				node.interval=0;
			}else{
				if(node.data.parentVersionId==lastNode.data.vId){
					//当前节点和上一节点是父子关系
					pt.x+=210,
					pt.y+=30;
					var nPt={};
					nPt.x=pt.x;
					nPt.y=pt.y;
					node.point=nPt;
				}else if(node.data.parentVersionId==lastNode.data.parentVersionId){
					//当前节点和上一节点是兄弟关系
					pt.y=lastNode.point.y+50;
					var nPt={};  
					nPt.x=pt.x;
					nPt.y=pt.y;
					node.point=nPt;
				}else{
					//当前节点和上一节点是叔侄关系	
					//找到当前节点的最近兄弟节点，并且将改点设为lastNode
					for(var j=i-1;j>=0;j--){
						var broNode=newArray[j];
						if(broNode.data.parentVersionId==node.data.parentVersionId){
							lastNode=broNode;
							break;
						}
					}
					//按兄弟关系处理
					// pt=lastNode.point;
					var nPt={};
					nPt.x=lastNode.point.x;
					nPt.y=pt.y+30;
					node.point=nPt;
					pt={
						x:nPt.x,
						y:nPt.y
					};
				}
			}
			lastNode=node;
		}

		global.height+=pt.y;

		return newArray;
	};

	//遍历树，把节点加入根目录中。先序遍历树
	var _travelTree=function(tree){
		var queue=new Queue();
		for(var i=0;i<tree.length;i++){
			_returnQueue(tree[i],queue);
		}

		return queue;
	};

	var _returnQueue=function(node,queue){
		var children=node.childrenVersion;
		queue.EnQueue(node);
		if((typeof children)!='undefined'&&children.length>0){
			for (var i = 0; i < children.length; i++) {
				_returnQueue(children[i],queue);
			};
		}
	};

	//广度优先遍历树，即按层次遍历树
	var _levelSearchTree=function(tree){
		var tempQueue=new Queue();
		tempQueue.EnQueue(tree);
		var tempArray=[];
		while(!tempQueue.IsEmpty()){
			var node=tempQueue.DeQueue();
			tempArray.push(node);
			var children=node.childrenVersion;
			if(typeof children!='undefined'&&children.length>0){
				for(var i=0;i<children.length;i++){
					tempQueue.EnQueue(children[i]);
				}
			}
		}

		var newArray=[];
		for(var i=1;i<tempArray.length;i++){
			newArray.push(tempArray[i]);
		}
		return newArray;
	};

	//画线
	var _drawLine=function(levelArray){
		var tempQueue=new Queue();
		for(var i=0;i<levelArray.length;i++){
			tempQueue.EnQueue(levelArray[i]);
		}
		var array=[];
		while(!tempQueue.IsEmpty()){
			var length=array.length;
			if(length==0){
				array.push(tempQueue.DeQueue());
			}else{
				var lastNode=array[length-1];
				var currentNode=tempQueue.GetHead();
				if(lastNode.data.parentVersionId==currentNode.data.parentVersionId){
					array.push(tempQueue.DeQueue());
				}else{
					var pointArray=[];
					for(var i=0;i<array.length;i++){
						pointArray.push(array[i].point);
					}

					if(array[0].data.parentVersionId=='0'){
						_drawMainLine(pointArray);
					}else{
						_drawSubline(pointArray);
					}
					array=new Array();
				}
			}
		}

		if(array.length!=0){
			var pointArray=[];
			for(var i=0;i<array.length;i++){
				pointArray.push(array[i].point);
			}

			if(array[0].data.parentVersionId=='0'){
				_drawMainLine(pointArray);
			}else{
				_drawSubline(pointArray);
			}
			array=new Array();
		}

	};

	//画主线
	var _drawMainLine=function(pointArray){
		var a=[];
		var beginStart={};
		var lastPoint={};
		for(var i=0;i<pointArray.length;i++){
			var pt=pointArray[i];
			if(i==0){
				beginStart.x=pt.x;
				beginStart.y=pt.y+50;
				a.push(beginStart.x+','+beginStart.y);
			}
			a.push(pt.x+','+pt.y);
			if(i==pointArray.length-1){
				lastPoint=pt;
			}
		}
		a.push(lastPoint.x+','+(lastPoint.y-50));
		var mainLineStr='<path class="branch" fill="none" stroke="'+options.mainLineColor+'" d="M'+a.join('L')+'" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>';
		var beginPointStr='<circle class="mainPoint" cx="'+beginStart.x+'" cy="'+beginStart.y+'" r="10" stroke="#fff" stroke-width="2" fill="#cc0000"></circle>';
		cvs.push(mainLineStr);
		cvs.push(beginPointStr);
	};

	var _drawSubline=function(pointArray){
		var a=[];
		var lastPoint={};
		for(var i=0;i<pointArray.length;i++){
			var pt=pointArray[i];
			if(i==0){
				a.push((pt.x-210)+','+(pt.y+30));
				a.push((pt.x-10)+','+(pt.y+30));
			}
			if(i==pointArray.length-1){
				lastPoint=pt;
			}
			a.push(pt.x+','+pt.y);
		}
		a.push(lastPoint.x+','+(lastPoint.y-20));
		a.push((lastPoint.x-2)+','+(lastPoint.y-16));
		a.push((lastPoint.x+2)+','+(lastPoint.y-16));
		a.push(lastPoint.x+','+(lastPoint.y-20));
		var htmlStr='<path class="branch" fill="none" stroke="'+options.subLineColor+'" d="M'+a.join('L')+'" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>';
		cvs.push(htmlStr);
	};

	//画点
	var _drawLinePoint=function(point,color){
		var htmlStr='<circle class="" cx="'+point.x+'" cy="'+point.y+'" r="5" stroke="#fff" stroke-width="2" fill="'+color+'"></circle>';
		return htmlStr;
	};

	//画点并且填充信息
	var _drawPointAndInfo=function(node,color){
		var point=node.point;
		var data=node.data;
		var project=node.projectList;
		var str=JSON.stringify(node);
		str=str.replace(/\"/g, "\'");//转换成单引号
		var htmlStr='<circle data-node="'+str+'" class="mainPoint" cx="'+point.x+'" cy="'+point.y+'" r="5" stroke="#fff" stroke-width="2" fill="'+color+'"></circle>';
		return htmlStr;
	};

	//项目描述
	var _drawProjectDes=function(node){
		//初始点
		var point=node.point;

		var subLinelastPoint={
			x:point.x+190,
			y:point.y
		};

		var textArrow=_drawTextArrow(subLinelastPoint);

		var textWrap=_drawTextWrap(subLinelastPoint);

		
		cvs.push(textArrow);
		cvs.push(textWrap);

	};

	//根据版本信息数组画版本信息
	var _drawVersionText=function(nodeArray){
		for(var i=0;i<nodeArray.length;i++){
			var node=nodeArray[i];
			_drawVersionDes(node);
		}
	};

	//版本描述
	var _drawVersionDes=function(node){
		//初始点
		var point=node.point;

		var textArrow=_drawTextArrow(point);

		var textWrap=_drawTextWrap(point);

		var data=node.data;

		var text=_drawText(point,data);

		cvs.push(textArrow);
		// cvs.push(textWrap);
		// cvs.push(text);
	};

	var _drawText=function(point,data){
		var pt={
			x:point.x-168,
			y:point.y-25
		};
		var htmlStr='<text x="'+(pt.x+3)+'" y="'+(pt.y)+'" style="fill:red;">'
			+'<tspan x="'+(pt.x+3)+'" y="'+(pt.y+15)+'">'+data.createTime+'</tspan>'
			+'<tspan x="'+(pt.x+3)+'" y="'+(pt.y+30)+'">'+data.version+'</tspan></text>';
		return htmlStr;
	};

	//画文本框
	var _drawTextWrap=function(point){
		var htmlStr='<rect class="textWrap" stroke="'+options.textWrapColor+'" width="150" height="45" x="'+(point.x-168)+'" y="'+(point.y-25)+'" r="0" rx="0" ry="0" fill="none" ></rect>';
		return htmlStr;
	};

	//画文字框的箭头
	var _drawTextArrow=function(point){
		var points=[
		];

		var p1=[
			point.x-10,
			point.y
		];

		var p2=[
			point.x-18,
			point.y+5
		];

		var p3=[
			point.x-18,
			point.y-5
		];
		points.push(p1.join(","));
		points.push(p2.join(","));
		points.push(p3.join(","));
		var htmlStr='<path class="textArrow" fill="'+options.textArrowColor+'" stroke="none" stroke-width="2" d="M'+points.join('L')+'Z"></path>';
		return htmlStr;
	};
	
	var _loadData=function(url){
		return {
			    data: {
			        list: [{
			            childrenVersion: [{
			                childrenVersion: [{
			                    data: {
			                        createTime: "2014-02-03",
			                        creator: "111111",
			                        description: "第一版本第一次修改上再次修改",
			                        parentVersionId: "222222222222222",
			                        role: "SUB_LINE",
			                        vId: "4444444444444",
			                        version: "1.1.1"
			                    },
			                    projectList: []
			                }, {
			                    childrenVersion: [{
			                        data: {
			                            createTime: "2014-02-07",
			                            creator: "11111",
			                            description: "第一版本第一次修改后的第二次修改",
			                            parentVersionId: "555555555555",
			                            role: "SUB_LINE",
			                            vId: "6666666666",
			                            version: "1.1.2.1"
			                        },
			                        projectList: []
			                    }],
			                    data: {
			                        createTime: "2014-02-04",
			                        creator: "111111",
			                        description: "第一版本第一次修改后的第二次修改",
			                        parentVersionId: "222222222222222",
			                        role: "SUB_LINE",
			                        vId: "555555555555",
			                        version: "1.1.2"
			                    },
			                    projectList: []
			                }, {
			                    childrenVersion: [{
			                        data: {
			                            createTime: "2014-02-09",
			                            creator: "11111",
			                            description: "1.1.3.1Version",
			                            parentVersionId: "777777777777",
			                            role: "SUB_LINE",
			                            vId: "88888888888",
			                            version: "1.1.3.1"
			                        },
			                        projectList: []
			                    }],
			                    data: {
			                        createTime: "2014-02-08",
			                        creator: "11111",
			                        description: "1.1.3版本",
			                        parentVersionId: "222222222222222",
			                        role: "SUB_LINE",
			                        vId: "777777777777",
			                        version: "1.1.3"
			                    },
			                    projectList: []
			                }],
			                data: {
			                    createTime: "2014-02-02",
			                    creator: "111111",
			                    description: "第一版本修改",
			                    parentVersionId: "00000000000000",
			                    role: "SUB_LINE",
			                    vId: "222222222222222",
			                    version: "1.1.0"
			                },
			                projectList: []
			            }, {
			                data: {
			                    createTime: "2014-02-05",
			                    creator: "GOD",
			                    description: "第一版本第二次修改",
			                    parentVersionId: "00000000000000",
			                    role: "SUB_LINE",
			                    vId: "333333333333333",
			                    version: "1.2.0"
			                },
			                projectList: []
			            }],
			            data: {
			                createTime: "2014-02-01",
			                creator: "GOD",
			                description: "初始版本",
			                parentVersionId: "0",
			                role: "MAIN_LINE",
			                vId: "00000000000000",
			                version: "1.0.0"
			            },
			            projectList: []
			        }, {
			            childrenVersion: [{
			                data: {
			                    createTime: "2014-02-10",
			                    creator: "11111",
			                    description: "2.1.0Version",
			                    parentVersionId: "111111111111",
			                    role: "SUB_LINE",
			                    vId: "999999999999",
			                    version: "2.1.0"
			                },
			                projectList: []
			            }],
			            data: {
			                createTime: "2014-02-06",
			                creator: "GOD",
			                description: "第二版本",
			                parentVersionId: "0",
			                role: "MAIN_LINE",
			                vId: "111111111111",
			                version: "2.0.0"
			            },
			            projectList: []
			        }],
			        page: {
			            currentCount: 2,
			            currentPage: 0,
			            limitCount: 2147483647,
			            totalCount: 2,
			            totalPage: 1
			        }
			    },
			    msg: "",
			    result: true
			};
	};

})(jQuery);